package object;

import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Test2 {
    public static void main(String[] args) {
      MysqlDataSource mysqlDataSource = new MysqlDataSource();
      mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/test?useSSL" +
              "=false&serverTimezone=UTC");
      mysqlDataSource.setUser("root");
      mysqlDataSource.setPassword("237912");
      DataSource dataSource = mysqlDataSource;

      Connection connection = null;
      PreparedStatement statement = null;
      ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            String sql = "select id, name, age, gender from student where name = ?";
            statement = connection.prepareStatement(sql);

            System.out.println("请输入要查询的名字：");
            Scanner scanner = new Scanner(System.in);
            String inputName = scanner.next();

            statement.setString(1, inputName);
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                Long id = resultSet.getLong("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                boolean gender = resultSet.getBoolean("gender");
                System.out.println(MessageFormat.format("id: {0}, name: {1}, age: {2}, gender: {3}"
                        , id, name, age, gender));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
